﻿using System;
using System.Diagnostics;
using System.IO;
using NewLife.Log;

namespace GitPuller
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            XTrace.UseConsole();
            var root = GitPullerConfig.Current.Root;
            XTrace.WriteLine($"ROOT:{root}");
            LoadChild(root);
        }

        private static void LoadChild(string dir)
        {
            XTrace.WriteLine($"检测目录：{dir}");
            try
            {
                var name = Path.GetFileName(dir);
                if (GitPullerConfig.Current.Ignore.Contains(name))
                {
                    XTrace.WriteLine("忽略:" + name);
                    return;
                }

                var children = Directory.GetDirectories(dir);
                foreach (var child in children)
                {
                    if (!Directory.Exists(child))
                    {
                        continue;
                    }

                    var git = Path.Combine(child, ".git", "index");
                    if (File.Exists(git))
                    {
                        Pull(child);
                    }
                    else
                    {
                        LoadChild(child);
                    }
                }
            }
            catch (Exception e)
            {
                XTrace.WriteException(e);
            }
        }

        private static void Pull(string dir)
        {
            XTrace.WriteLine($"Git Pull:{dir}");
            var process = new Process
            {
                StartInfo =
                {
                    Arguments = "pull",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    FileName = "git",
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    WorkingDirectory = dir
                }
            };
            process.Start();
            using (var p = process.StandardOutput)
            {
                while (!p.EndOfStream)
                {
                    XTrace.WriteLine(p.ReadLine());
                }
            }
        }
    }
}